using System;
using System.IO;
using System.Linq;
using Servlets.Exceptions;
using Servlets.Api;

namespace Servlets.Http
{
	public class UrlEncodedBody : IBody
	{
		public object this [string key]{get{
				string val = Value[key];
				if(val == null) {
					throw new InvalidKeyException(key);
				}
				return Value[key];
			}
		}
		
		public byte[] RawBody{get;private set;}
		public IValue<string> Value{get;private set;}
		
		/// <summary>
		/// ** NOT IMPLEMENTED **
		/// </summary>
		public IValue<WebFile> File{get{throw new MethodNotImplementedException("File");}}
				
		public void ParseStream(StreamReader reader, string contentType, int contentLength) {
			char[] buffer = new char[contentLength];
			reader.ReadBlock(buffer, 0, buffer.Length);
			string content = new string(buffer);
			RawBody = buffer.Select(c => (byte)c).ToArray();
			Value = new QueryString(content);
			Console.WriteLine (Value);
		}
	}
}

